from osv import fields, osv
from tools.translate import _


class res_partner(osv.osv):
    _description ='Partner'
    _name = 'res.partner'
    _inherit='res.partner'    

    def _newcode_suggest(self,cr,uid,context={}):
        selection=[]
#New code HCM
        cr.execute("Select newcode from vwnewcode_partner")
        for x in cr.fetchall():            
            selection.append((x[0],x[0]))
        return selection
    
    def _onchange_suggest_code(self, cr, uid, ids,new_code):
        if new_code:
            val={'value':{'ref':new_code,'newcode_suggest':False}}
        else:
            val={}
        return val
    
    
    def _parter_address_fnc(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids_lst=",".join(map(str,ids))
            
            cr.execute("Select rp.id,street || case when coalesce(city,'0')='0' then '' else ', ' || city end as address\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids_lst)) #coalesce(partner_id,0)>0 and partner_
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    def _parter_tel(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids=",".join(map(str,ids))
            cr.execute("Select rp.id,phone\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids))
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    def _parter_fax(self, cr, uid, ids, name, arg, context=None):
        res={}
        if ids:
            tmp_list=[]
            partner_ids=",".join(map(str,ids))
            cr.execute("Select rp.id,fax\
                         from res_partner rp left join res_partner_address on rp.id = partner_id\
                         where rp.id in (%s)" % (partner_ids))
            for id,addr in cr.fetchall():
                if id not in tmp_list:
                    res[id] =addr
                    tmp_list.append(id)            
        return res
    
    _columns={
             'address_default':fields.function(_parter_address_fnc,type='char',string="Address",size=254,method=True),
             'tel_default':fields.function(_parter_tel,type='char',string="Phone",size=20,method=True),
             'fax_default':fields.function(_parter_fax,type='char',string="Fax",size=20,method=True),

             'ref':fields.char('Code', size=64,required=True),
             'trade_name':fields.char('Trade Name',size=25),
             'vat_code':fields.char('N.P.W.P.',size=25),
             'nppkp_code':fields.char('N.P.P.K.P.',size=25),             
             'newcode_suggest':fields.selection(_newcode_suggest,'New Code',size=16,store=False),#,readonly=True,states={'draft':[('readonly',False)]}
             }
    _defaults={
               'customer': lambda *a: False,
               'supplier': lambda *a: 1,
               }
    _sql_constraints = [
        ('code_uniq', 'unique (ref)', 'The Code of the Partner must be unique !')
    ]
    def _new_type_def(self, cr, uid, context):
        typeoforder = False
        if context:
            if 'typeoforder' in context:
                typeoforder = context['typeoforder']
        return typeoforder
res_partner()

class res_partner_bank(osv.osv):
    '''Bank Accounts'''
    _name = "res.partner.bank"
    _rec_name = "acc_number"
    _inherit='res.partner.bank'
    _order = 'sequence'

    def _bank_type_get(self, cr, uid, context=None):
        bank_type_obj = self.pool.get('res.partner.bank.type')

        result = []
        type_ids = bank_type_obj.search(cr, uid, [])
        bank_types = bank_type_obj.browse(cr, uid, type_ids, context=context)
        for bank_type in bank_types:
            result.append((bank_type.code, bank_type.name))
        return result

    def _default_value(self, cursor, user, field, context=None):
        if field in ('country_id', 'state_id'):
            value = False
        else:
            value = ''
        if not context.get('address', False):
            return value
        for ham, spam, address in context['address']:
            if address.get('type', False) == 'default':
                return address.get(field, value)
            elif not address.get('type', False):
                value = address.get(field, value)
        return value

    _columns = {
        'name': fields.char('Description', size=128),
        'acc_number': fields.char('Account Number', size=64, required=False),
        'bank': fields.many2one('res.bank', 'Bank'),
        'owner_name': fields.char('Account Owner', size=64),
        'street': fields.char('Street', size=128),
        'zip': fields.char('Zip', change_default=True, size=24),
        'city': fields.char('City', size=128),
        'country_id': fields.many2one('res.country', 'Country',
            change_default=True),
        'state_id': fields.many2one("res.country.state", 'State',
            change_default=True, domain="[('country_id','=',country_id)]"),
        'partner_id': fields.many2one('res.partner', 'Partner', required=True,
            ondelete='cascade', select=True),
        'state': fields.selection(_bank_type_get, 'Bank Type', required=True,
            change_default=True),
        'sequence': fields.integer('Sequence'),
    }
    _defaults = {
        'owner_name': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'name', context=context),
        'street': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'street', context=context),
        'city': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'city', context=context),
        'zip': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'zip', context=context),
        'country_id': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'country_id', context=context),
        'state_id': lambda obj, cursor, user, context: obj._default_value(
            cursor, user, 'state_id', context=context),
    }

    def fields_get(self, cr, uid, fields=None, context=None):
        res = super(res_partner_bank, self).fields_get(cr, uid, fields, context)
        bank_type_obj = self.pool.get('res.partner.bank.type')
        type_ids = bank_type_obj.search(cr, uid, [])
        types = bank_type_obj.browse(cr, uid, type_ids)
        for type in types:
            for field in type.field_ids:
                if field.name in res:
                    res[field.name].setdefault('states', {})
                    res[field.name]['states'][type.code] = [
                            ('readonly', field.readonly),
                            ('required', field.required)]
        return res

    def name_get(self, cr, uid, ids, context=None):
        if not len(ids):
            return []
        res = []
        for id in self.browse(cr, uid, ids):
            acc_no = id.acc_number
            bk_name=''
            if id.bank:
                bk_name=' - ' + id.bank.name
            full_bank_account = acc_no + bk_name
            res.append((id.id,full_bank_account))
        return res

res_partner_bank()